package com.wnxy.sk.member.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.sk.common.constant.RedisKey;
import com.wnxy.sk.common.exception.Assert;
import com.wnxy.sk.common.jwt.JwtTemplate;
import com.wnxy.sk.common.result.enums.impl.BusinessCode;
import com.wnxy.sk.member.dto.UserDto;
import com.wnxy.sk.member.entity.User;
import com.wnxy.sk.member.mapper.UserMapper;
import com.wnxy.sk.member.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;

/**
 * <p>
 * 会员用户表 服务实现类
 * </p>
 *
 * @author Jet
 * @since 2022-10-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtTemplate jwtTemplate;

    @Override
    public String login(UserDto userDto) {
        //1. 根据手机号查询
        String mobile = userDto.getMobile();
        Wrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUserMobile, mobile);
        User user = this.getOne(wrapper);

        //2. 判断：手机号码为空，返回异常
        Assert.error(user,BusinessCode.LOGIN_FAIL);

        //3. 判断密码
        boolean flag = BCrypt.checkpw(userDto.getPassword(),user.getLoginPassword());
        Assert.error(flag,BusinessCode.LOGIN_FAIL);

        //4. 生成token
        Map<String,Object> map = MapUtil.createMap(Map.class);
        map.put("userId",user.getUserId());
        String token = jwtTemplate.createToken(map);

        //5. 保存token到redis中，设置有效时间30分钟.   user:token:id  AABBCC
        redisTemplate.opsForValue().set(
                RedisKey.USER_TOKEN+":"+user.getUserId(),
                token,
                Duration.ofMinutes(30)
        );
        return token;
    }
}
